package com.lp.yupao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lp.yupao.common.ErrorCode;
import com.lp.yupao.exception.BusinessException;
import com.lp.yupao.mapper.UserMapper;
import com.lp.yupao.model.domain.User;
import com.lp.yupao.service.UserService;
import com.lp.yupao.utils.AlgorithmUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.util.Pair;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.stream.Collectors;

import static com.lp.yupao.constant.RedisKey.RECOMMEND_KEY;
import static com.lp.yupao.constant.UserConstant.USER_LOGIN_STATUS;
import static java.util.regex.Pattern.compile;

/**
 * @author lp337
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-03-12 18:05:52
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate redisTemplate;

    private static final String SALT = "yupi";

    /**
     * 用户登录校验
     *
     * @param userAccount   用户名
     * @param userPassword  用户密码
     * @param checkPassword 用于校验的密码
     * @return 用户id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {
        // 1.校验
        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        // 账户是否小于4位
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号长度小于4位");
        }
        // 密码是否小于8位
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度小于8位");
        }
        //判断星球编号是否大于6位
        if (planetCode.length() > 6) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号大于6位");
        }
        // 账户是否包含特殊字符
        String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\\n|\\r|\\t";//包含特殊字符
        Matcher matcher = compile(regEx).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户包含特殊字符");
        }
        // 密码与校验密码是否相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码不相同");
        }
        // 判断账户名是否被使用
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count >= 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户已被注册");
        }
        // 判断星球编号是否重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode", planetCode);
        count = userMapper.selectCount(queryWrapper);
        if (count >= 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号重复");
        }
        // 2.加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户保存失败");
        }
        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户名
     * @param userPassword 用户密码
     * @param request
     * @return 用户脱敏的信息
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1.校验
        if (StringUtils.isAllBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        // 账户是否小于4位
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号长度小于4位");
        }
        // 密码是否小于8位
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度小于8位");
        }
        // 账户是否包含特殊字符
        String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\\n|\\r|\\t";//包含特殊字符
        Matcher matcher = compile(regEx).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号包含特殊字符");
        }
        // 2.加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 判断账户名是否被使用
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        // 判断用户是否存在
        if (user == null) {
            log.info("用户账户或密码错误!");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号或密码错误");
        }
        // 3.用户信息脱敏
        User safetyUser = getSafetyUser(user);
        // 4.保存用户信息到session中
        request.getSession().setAttribute(USER_LOGIN_STATUS, safetyUser);
        return safetyUser;
    }

    /**
     * 用户脱敏
     *
     * @param user 需要脱敏的用户
     * @return 脱敏后端用户
     */
    @Override
    public User getSafetyUser(User user) {
        if (user == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User safetyUser = new User();
        safetyUser.setId(user.getId());
        safetyUser.setUserName(user.getUserName());
        safetyUser.setAvatarUrl(user.getAvatarUrl());
        safetyUser.setUserAccount(user.getUserAccount());
        safetyUser.setGender(user.getGender());
        safetyUser.setPhone(user.getPhone());
        safetyUser.setEmail(user.getEmail());
        safetyUser.setUserStatus(user.getUserStatus());
        safetyUser.setCreateTime(user.getCreateTime());
        safetyUser.setUserRole(user.getUserRole());
        safetyUser.setPlanetCode(user.getPlanetCode());
        safetyUser.setTags(user.getTags());
        safetyUser.setUserProfile(user.getUserProfile());
        return safetyUser;
    }

    /**
     * 查询用户信息(通过userName)
     *
     * @param userName 用户名
     * @param request  请求头
     * @return 用户信息
     */
    @Override
    public List<User> selectUserByUserName(String userName, HttpServletRequest request) {
        // 1.判断是否是管理员
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "用户没有管理员权限");
        }
        // 2.从数据库中查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(userName)) {
            queryWrapper.like("userName", userName);
        }
        List<User> userList = userMapper.selectList(queryWrapper);
        // 3.用户脱敏
        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());
    }

    /**
     * 获取用户登录态
     *
     * @param request 请求头
     * @return user对象
     */
    @Override
    public User getCurrentUser(HttpServletRequest request) {
        User currentUser = (User) request.getSession().getAttribute(USER_LOGIN_STATUS);
        // todo 判断用户是否有效
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "用户未登录");
        }
        //从数据库中获取用户信息
        Long userId = currentUser.getId();
        User user = userMapper.selectById(userId);
        return getSafetyUser(user);
    }

    /**
     * 注销
     *
     * @param request 请求头
     * @return user对象
     */
    @Override
    public Integer userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATUS);
        return 1;
    }

    /**
     * 通过id删除用户信息
     *
     * @param userId 用户id
     * @return 是否删除成功 成功为 1
     */
    @Override
    public Integer deleteUserById(Long userId, HttpServletRequest request) {
        //判断登录的用户是否是管理员
        boolean result = isAdmin(request);
        if (result) {
            throw new BusinessException(ErrorCode.NO_AUTH, "您不是管理员");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", userId);
        User deleteUser = userMapper.selectOne(queryWrapper);
        return userMapper.deleteById(deleteUser);
    }

    /**
     * 根据标签查找用户
     *
     * @param tagsNameList 标签列表
     * @return
     */
    @Override
    public List<User> searchUserByTags(List<String> tagsNameList) {
        // 判断参数是否为空
        if (CollectionUtils.isEmpty(tagsNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 使用内存查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        Gson gson = new Gson();
        // 查询所有用户信息
        List<User> userList = userMapper.selectList(queryWrapper);
        return userList.stream().filter(user -> {
            // 获取用户的标签列表
            String tagStr = user.getTags();
            // 判断用户的标签列表是否为空
            if (StringUtils.isBlank(tagStr)) {
                return false;
            }
            // 序列化
            Set<String> tagsList = gson.fromJson(tagStr, new TypeToken<Set<String>>() {
            }.getType());
            for (String tagName : tagsList) {
                if (!tagsList.contains(tagName)) {
                    return false;
                }
            }
            return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());
    }

    /**
     * 根据标签查找用户(SQL 查询)
     *
     * @param tagsNameList 标签列表
     * @return
     */
    @Override
    public List<User> searchUserByTagsBySql(List<String> tagsNameList) {
        // 判断参数是否为空
        if (CollectionUtils.isEmpty(tagsNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 使用sql查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        for (String tagName : tagsNameList) {
            // 拼接sql语句
            queryWrapper = queryWrapper.like("tags", tagName);
        }
        List<User> userList = userMapper.selectList(queryWrapper);
        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());
    }

    /**
     * 更新用户数据
     *
     * @param user      新的用户数据
     * @param LoginUser 登录用户信息
     * @return 是否修改成功
     */
    @Override
    public int updateUser(User user, User LoginUser) {
        long userId = user.getId();
        long loginUserId = LoginUser.getId();
        // 如果不是管理员也不是本人，不允许修改
        if (!isAdmin(LoginUser) && userId != loginUserId) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        // 修改数据
        int result = userMapper.updateById(user);
        if (result == 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        return result;
    }

    /**
     * 获取登录用户
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        User loginUser = (User) request.getSession().getAttribute(USER_LOGIN_STATUS);
        // 判断是否获取到登录用户
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        return loginUser;
    }

    /**
     * 判断用户是否位管理员（传请求）
     *
     * @param request 请求
     * @return 是否位管理员
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATUS);
        Integer userRole = user.getUserRole();
        if (user == null || userRole == 0) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        return true;
    }

    /**
     * 判断用户是否位管理员（传登录用户）
     *
     * @param loginUser 登录用户
     * @return 是否位管理员
     */
    @Override
    public boolean isAdmin(User loginUser) {
        Integer userRole = loginUser.getUserRole();
        if (loginUser == null || userRole == 0) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        return true;
    }

    /**
     * 分页查询用户数据
     *
     * @param pageNum  第几页
     * @param pageSize 每页大小
     * @param request  请求
     * @return 用户列表
     */
    @Override
    public Page<User> recommendUsers(long pageNum, long pageSize, HttpServletRequest request) {
        // 尝试先从缓存中获取用户信息
        User loginUser = getLoginUser(request);
        String redisKey = RECOMMEND_KEY + loginUser.getId();
        Page<User> userPage = (Page<User>) redisTemplate.opsForValue().get(redisKey);
        if (userPage != null) {
            System.out.println("查询缓存");
            return userPage;
        }
        // 从数据库中查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        userPage = userMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);
        // 写缓存
        try {
            redisTemplate.opsForValue().set(redisKey, userPage, 30000, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.info("redis set error:" + e);
            System.out.println("写入失败");
        }
        return userPage;
    }

    /**
     * 随机匹配用户
     *
     * @param num       匹配的用户数
     * @param loginUser 登录用户
     * @return 用户列表
     */
    @Override
    public List<User> matchUserList(int num, User loginUser) {
        // 查询所有的用户信息（过滤标签为空的）
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.isNotNull("tags");
        List<User> userList = userMapper.selectList(userQueryWrapper);
        String loginUserTags = loginUser.getTags();
        // 保存结果的集合 (用户信息 ，相似度)
        List<Pair<User, Integer>> list = new ArrayList<>();
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            // 过滤本人
            if (user.getId() == loginUser.getId()) {
                continue;
            }
            String userTags = user.getTags();
            int score = AlgorithmUtils.minDistance(loginUserTags, userTags);
            list.add(new Pair<>(user, score));
        }
        // score升序排序取前num个记录
        List<Pair<User, Integer>> pairList = list.stream()
                .sorted((o1, o2) -> o1.getValue() - o2.getValue())
                .limit(num)
                .collect(Collectors.toList());
        // 过滤,封装
        ArrayList<User> users = new ArrayList<>();
        for (Pair<User, Integer> pair : pairList) {
            User user = pair.getKey();
            users.add(getSafetyUser(user));
        }
        return users;
    }
}




